<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/23
 * Time: 10:39
 * 总部
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\AgentShipment;
use app\common\model\AgentShop;
use app\common\model\Commission;
use app\common\service\UserService;
use think\Db;

class Shop extends Api {
	
	/**
	 * 统计
	 */
	public function statistics() {
		$userId = $this->auth->id;
		$level = $this->auth->level;
		$isAdmin = false;
		if($level != \app\admin\model\User::LEVEL_SHOP) {
			$adminLevel = \app\common\model\AgentAdmin::getAdminLevel($userId);
			if(!$adminLevel || $adminLevel['role'] != \app\admin\model\User::LEVEL_SHOP) {
				$this->error('权限不足');
			}
			$isAdmin = true;
			$userId = $adminLevel['user_id'];
		}
		
		$agentInfo = Db::name('agentShop')
			->where(['user_id' => $userId])
			->field('name, image, sale_number, order_number, sale_amount, id, status')
			->find();
		
		if(!$agentInfo || $agentInfo['status'] == AgentShop::STATUS_D) {
			$this->error('当前身份已被禁用');
		}
		
		//访客数
//		$visible = Db::name('Visitor')->where(['share_user_id' => $userId])->count();
		
		//粉丝
		$fans = UserService::getFansNumById($userId);
		
		//推广员
		$promotion = Db::name('promotion')
			->where(['recommend_user_id' => $userId, 'status' => \app\common\model\Promotion::STATUS_Y])
			->count();
		
		//库存
		$stock = Db::name('agentStock')->where(['user_id' => $userId])->sum('number');
		
		//销售佣金
		$saleCommission = Db::name('commission')->where(['user_id' => $userId, 'type' => ['in', [Commission::TYPE_SALE, Commission::TYPE_RECOMMEND]]])->sum('amount');
		
		//提货佣金
		$goodsCommission = Db::name('commission')->where(['user_id' => $userId, 'type' => Commission::TYPE_GOODS])->sum('amount');
		$orderNumber = Db::name('agentShipment')->where(['sign_agent_id' => $agentInfo['id'], 'status' => AgentShipment::STATUS_WAIT])->count();
		
		//我的奖励数量
		$user = $this->auth->getUser();
		$selfNumber = $user['reward_number'];
		
		$this->success('查询成功', [
			'fans' => $fans,
			'order_number' => $agentInfo['order_number'],
			'sale_number' => $agentInfo['sale_number'],
			'order_amount' => $agentInfo['sale_amount'],
//			'visible' => $visible,
			'stock_order_number' => $orderNumber,
			'promotion' => $promotion,
			'sale_commission' => $saleCommission,
			'goods_commission' => $goodsCommission,
			'stock' => $stock,
			'self_number' => $selfNumber,
			'agentInfo' => $agentInfo,
			'is_admin' => $isAdmin
		]);
	}
	
	
	
}
